package per.yhh.xxxtsj.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import per.yhh.xxxtsj.Utils.JWTUtils;
import per.yhh.xxxtsj.entity.Good;
import per.yhh.xxxtsj.entity.Message;
import per.yhh.xxxtsj.entity.Myorder;
import per.yhh.xxxtsj.entity.User;
import per.yhh.xxxtsj.service.GoodService;
import per.yhh.xxxtsj.service.MyorderService;
import per.yhh.xxxtsj.service.OrderitemService;
import per.yhh.xxxtsj.service.UserService;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yhh
 * @since 2022-04-10
 */
@CrossOrigin
@RestController
@RequestMapping("/good")
public class GoodController {

    final
    GoodService goodService;
    final
    UserService userService;
    @Autowired
    MyorderService orderService;
    @Autowired
    OrderitemService orderitemService;
    public GoodController(GoodService goodService, UserService userService) {
        this.goodService = goodService;
        this.userService = userService;
    }

    @GetMapping("/goods")
    public Message goods(HttpServletRequest request, @RequestParam("query") String keyword, @RequestParam("pagenum") Integer pageNum, @RequestParam("pagesize") Integer pageSize) {
        String authorization = request.getHeader("Authorization");
        String account = JWTUtils.validateToken(authorization);
        User user = userService.getUserByAccount(account);
        if (user == null) return Message.failed();
        Integer permissions = user.getPermissions();
        if(permissions==2){
            return Message.ok(goodService.getGoodsByPageAndKeyAndId(user.getUid(),keyword,pageNum,pageSize));
        }
        return Message.ok(goodService.getGoodsByPageAndKey(keyword, pageNum, pageSize));
    }


    @PostMapping("/addgood")
    public Message addGood(HttpServletRequest request, @RequestBody Good good) {
        String authorization = request.getHeader("Authorization");
        String account = JWTUtils.validateToken(authorization);
        User user = userService.getUserByAccount(account);
        if (user == null || user.getPermissions() >= 3) {
            return Message.failed();
        }
        good.setUid(user.getUid());
        if (goodService.addGood(good)) {
            return Message.ok(null);
        }
        return Message.failed();
    }

    @GetMapping("/buy/{gid}")
    public Message buy(HttpServletRequest request,@PathVariable String gid){
        String authorization = request.getHeader("Authorization");
        String account = JWTUtils.validateToken(authorization);
        User user = userService.getUserByAccount(account);
        Good good = goodService.buy(user, Integer.valueOf(gid));
        Myorder order = orderService.buy(user, good);
        orderitemService.buy(user,good,order);

        return Message.ok(null);
    }
}

